<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px"><zs-fl-selector @chooseZsfl="handleZsfl"></zs-fl-selector></el-aside>
      <el-container>
        <el-header> <el-row :gutter="20">
            <el-col :span="18">
              <el-form :inline="true" class="demo-form-inline">
                <el-form-item>
                  <el-input v-model="queryData.keyWord" placeholder="请输入关键词" @keyup.enter="getDataList()"
                    style="width: 350px;" />
                </el-form-item>
                <el-form-item>
                  <el-select v-model="queryData.status" style="width: 120px" clearable placeholder="状态">
                    <el-option :value="null" label="所有" />
                    <el-option :value="'0'" label="未生效" />
                    <el-option :value="'1'" label="已生效" />
                    <el-option :value="'2'" label="已下线" />
                    <el-option :value="'3'" label="审核未通过" />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="getDataList()">
                查询
              </el-button>
              <el-button type="default" @click="resetData()">清空</el-button>
            </el-col>
          </el-row>
          <!-- 管理员不用添加知识 v-if='userinfo.yhlx===3'-->

          <el-row :gutter="12">
          <el-col :span="4"><el-button type="success" @click="add()" v-permission="'knowledge.add'">
            添加知识
          </el-button></el-col>
          <el-col :span="4">
            <el-dropdown split-button>
              导入
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="downloadTemplate">
                    <i-ep-download />下载模板</el-dropdown-item>
                  <el-dropdown-item @click="()=>{importDialogVisible = true}">
                    <i-ep-top />导入数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>

          <el-col :span="4"> <el-button type="danger" v-if="userinfo && userinfo.yhlx !== 3" :disabled="selectedIds.length === 0"
            @click="removeBatch()" v-permission="'knowledge.delete'">
            批量下线
          </el-button></el-col>
          </el-row>

          
          <!-- 只有管理员才能下线他人的知识 -->
         

        </el-header>
        <el-main><el-table :data="tableData" ref="multipleTableRef" @selection-change="handleSelectionChange"
            v-loading="loading" border stripe style="width: 100%" highlight-current-row>
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" width="70" align="center">
              <template #default="{ $index }">
                {{ (pageIndex - 1) * pageSize + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="知识库标题" width="180" align="center">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="auto">
                  <template #default>
                    <div>问题类型: {{ scope.row.wtlx }}</div>
                    <div>问题场景: {{ scope.row.wtcj }}</div>
                  </template>
                  <template #reference>
                    {{ scope.row.zsbt }}
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="wtnr" label="问题内容" width="220" align="center" />
            <el-table-column prop="hdnr" label="回答内容" width="220" align="center" />
            <!-- <el-table-column prop="fbz" label="发布者" /> -->
            <el-table-column label="知识状态" width="180" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.sfshenx == '0'" type="warning">审核中</el-tag>
                <el-tag v-if="scope.row.sfshenx == '1'" type="success">已生效</el-tag>
                <el-tag v-if="scope.row.sfshenx == '2'" type="info">已下线</el-tag>
                <el-tag v-if="scope.row.sfshenx == '3'" type="info">审核不通过</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200" align="center">
              <template #default="scope">
                <el-button link type="primary" v-permission="'knowledge.detail'"
                  @click="$router.push({ name: '知识详情', params: { id: scope.row.id } })">
                  详情
                </el-button>
                <el-button v-if="userinfo && userinfo.yhlx !== 3" link type="info" @click="edit(scope.row.id)"
                  v-permission="'knowledge.update'">
                  编辑
                </el-button>
                <el-button v-if="!scope.row.collected" link v-permission="'knowledge.collection'" type="warning"
                  @click="addSc(scope.row.id)">
                  收藏
                </el-button>
                <el-button link type="danger" @click="remove(scope.row.id)"
                  v-if="scope.row.sfshenx == '1' && userinfo && userinfo.yhlx !== 3" v-permission="'knowledge.delete'">
                  下线
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total"
            layout="total, sizes, prev, pager, next, jumper" />
          <!-- 添加修改对话框 -->
          <el-dialog v-model="dialogFormVisible" :title="dialogType + '知识'">
            <el-form :model="form" label-width="120px" ref="ruleFormRef" :rules="rules">
              <el-form-item label="知识标题:" prop="zsbt">
                <el-input v-model="form.zsbt" />
              </el-form-item>
              <el-form-item label="知识分类:" prop="zslxIds">
                <div class="m-4">
                  <el-cascader v-model="form.zslxIds" :options="options" :props="props" />
                </div>
              </el-form-item>
              <el-form-item label="问题内容:" prop="wtnr">
                <el-input v-model="form.wtnr" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
              </el-form-item>
              <el-form-item label="问题同义句">
                <el-tag v-for="tag in wttyjTags" :key="tag" class="mx-1" closable :disable-transitions="false"
                  @close="handleClose(tag, true)">
                  {{ tag }}
                </el-tag>

                <el-input v-if="wtInputVisible" ref="wtInputRef" v-model="wtInputValue" class="ml-1 w-20" size="small"
                  @keyup.enter="handleInputConfirm(true)" @blur="handleInputConfirm(true)" />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(true)">
                  + 添加问题同义句
                </el-button>
              </el-form-item>
              <el-form-item label="回答内容:" prop="hdnr">
                <el-input v-model="form.hdnr" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
              </el-form-item>
              <el-form-item label="回答同义句:">
                <el-tag v-for="tag in hdtyjTags" type="success" :key="tag" class="mx-1" closable
                  :disable-transitions="false" @close="handleClose(tag, false)">
                  {{ tag }}
                </el-tag>
                <el-input v-if="hdInputVisible" ref="hdInputRef" v-model="hdInputValue" class="ml-1 w-20" size="small"
                  @keyup.enter="handleInputConfirm(false)" @blur="handleInputConfirm(false)" />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(false)">
                  + 添加回答同义句
                </el-button>
              </el-form-item>
              <el-form-item label="附件:">
                <!-- TODO 设置token再上传，否则无权限 -->
                <!-- 只能上传一个附件 -->
                <el-upload v-model:file-list="fileList" class="upload-demo" action="/api/file/upload" :limit="1"
                  :on-preview="handlePreview" :on-remove="handleRemove" :on-exceed="handleExceed"
                  :on-success="handleSuccess">
                  <el-button type="primary">点击上传文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      点击文件即可预览
                    </div>
                  </template>
                </el-upload>

              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="saveOrUpdate(ruleFormRef)">
                  确定
                </el-button>
              </span>
            </template>
          </el-dialog>


          <!-- 文件预览 -->
          <el-dialog v-model="preViewVisible" :width="'80%'">
            <preview :fileSuffix="fileSuffix" :imageSrc="imageSrc"></preview>
          </el-dialog>
             <!-- 导入弹窗 -->
     <el-dialog
      v-model="importDialogVisible"
      title="批量导入知识"
      width="600px"
      append-to-body
      @close="closeImportDialog"
    >
      <el-form label-width="80px">
        <el-form-item label="Excel">
          <el-upload
            class="upload-demo"
            action=""
            drag
            :auto-upload="false"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :file-list="excelFilelist"
            :on-change="handleExcelChange"
            :limit="1"
          >
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleZSImport">确 定</el-button>
          <el-button @click="closeImportDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { table } from 'console'
import { nextTick, reactive, ref } from 'vue'
import {
  getListApi,
  addZsApi,
  updateZsApi,
  getZsByIdApi,
  deleteZsApi,
  downloadTemplateApi,
  importZSApi,
} from '@/api/knowledgeBase/knowledge.js'
import { getTreeApi } from '@/api/knowledgeBase/typeTree.js'
import { addScApi } from '@/api/personal/collection.js'
import { deleleFileApi } from "@/api/oss";
import {
  ElInput,
  ElMessage,
  ElMessageBox,
  ElTable,
  FormInstance,
  FormRules,
} from 'element-plus'
import { useApp } from '@/pinia/modules/app'
// import { useUserinfo } from '@/components/Avatar/hooks/useUserinfo'
import type { UploadFile, UploadProps, UploadUserFile } from 'element-plus'
import preview from '@/components/Preview/index.vue'
import ZsFlSelector from '@/views/common/ZsFlSelector.vue'
import { useAccount } from '@/pinia/modules/account'
import { storeToRefs } from 'pinia'

// const userinfo = useUserinfo().userinfo
const { userinfo } = storeToRefs(useAccount())
const multipleTableRef = ref<InstanceType<typeof ElTable>>()

const { authorization } = useApp()
const dialogFormVisible = ref(false)
const dialogType = ref('')
const preViewVisible = ref(false)
const imageSrc = ref('')
const pageIndex = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const queryData = reactive({
  keyWord: '',
  status: null, // null表示所有知识，0表示未生效的知识，1表示已生效的知识，2表示已失效的知识
  zsfl: undefined
})
const form = ref({
  id: '',
  zsflmc: '',
  zsbt: '',
  zslxIds: [],
  fbzid: '',
  // fbz: '',
  wtnr: '',
  wttyj: '',
  hdnr: '',
  hdtyj: '',
  fj: '',
})

const wtInputValue = ref('')
const hdInputValue = ref('')
const wttyjTags = ref([]) // 问题同义句
const hdtyjTags = ref([]) // 回答同义句
const wtInputVisible = ref(false)
const hdInputVisible = ref(false)
const wtInputRef = ref<InstanceType<typeof ElInput>>()
const hdInputRef = ref<InstanceType<typeof ElInput>>()
const loading = ref(true)
const selectedIds = ref([]); // 被选中的id集合
const importDialogVisible = ref(false)
const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);
/**
 * 行checkbox change事件
 */
const handleSelectionChange = (selection: any) => {
  selectedIds.value = selection.map((item: any) => item.id);
}


// 点击分类
const handleZsfl = (zsflId: number) => {
  queryData.zsfl = zsflId

  console.log("知识分类为" + zsflId)
  // 触发查询
  getDataList()
}

// 附件列表  
const fileList = ref<UploadUserFile[]>([])
const fileSuffix = ref("")// 文件类型

// 移除文件
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file.url + "移除文件=================")
  deleleFileApi({ url: file.url })
}

// 预览
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log("预览文件")
  preViewVisible.value = true
  console.log(uploadFile.url + "==========================")
  imageSrc.value = uploadFile.url
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `只能上传一个文件 ！！！！`
  )
}

// 附件上传成功
const handleSuccess = (response, uploadFile, uploadFiles) => {
  // 设置文件地址
  console.log('后端返回的图片地址为' + response.data)

  // 拼接文件url  = http://ip:port/file/response.data  response.data
  uploadFile.url = response.data.url
  fileSuffix.value = (response.data.url == null || response.data.url == "") ? "" : response.data.url.split('.').pop()

  // 提示成功
  ElMessage({
    type: 'success',
    message: '文件上传成功',
  })
}
/**
 * 导入场景
 */
 function handleZSImport() {
    if (!excelFile.value) {
      ElMessage.warning("上传Excel文件不能为空");
      return false;
    }
    importZSApi(excelFile.value).then(({data}) => {
      ElMessage({
        duration:10000,
        showClose: true,    
        dangerouslyUseHTMLString: true,
        message: data,
        type:'success'
      });
      closeImportDialog();
      resetData();
    });
}

/**
 * 下载导入模板
 */
 const downloadTemplate = ()=>{
  downloadTemplateApi().then((response) => {
    const blob = new Blob([response.data]);
    /* const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
    }); */
    const a = document.createElement("a");
    const href = window.URL.createObjectURL(blob); // 下载链接
    a.href = href;
    a.download = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    ); // 获取后台设置的文件名称
    document.body.appendChild(a);
    a.click(); // 点击下载
    document.body.removeChild(a); // 下载完成移除元素
    window.URL.revokeObjectURL(href); // 释放掉blob对象
  });
}

/**
 * 关闭导入弹窗
 */
 function closeImportDialog() {
  importDialogVisible.value = false;
  excelFile.value = undefined;
  excelFilelist.value = [];
}
/**
 * Excel文件change事件
 *
 * @param file
 */
 function handleExcelChange(file: UploadFile) {
  if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
    ElMessage.warning("上传Excel只能为xlsx、xls格式");
    excelFile.value = undefined;
    excelFilelist.value = [];
    return false;
  }
  excelFile.value = file.raw;
}

// 移除之前操作
// const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
//   return ElMessageBox.confirm(
//     `Cancel the transfer of ${uploadFile.name} ?`
//   ).then(
//     () => {
//       console.log("取消成功")
//     }
//   )




const handleClose = (tag: string, isWt: boolean) => {
  if (isWt) {
    wttyjTags.value.splice(wttyjTags.value.indexOf(tag), 1)
  } else {
    hdtyjTags.value.splice(hdtyjTags.value.indexOf(tag), 1)
  }
}

const showInput = (isWt: boolean) => {
  if (isWt) {
    wtInputVisible.value = true
    nextTick(() => {
      wtInputRef.value!.input!.focus()
    })
  } else {
    hdInputVisible.value = true
    nextTick(() => {
      hdInputRef.value!.input!.focus()
    })
  }
}

const handleInputConfirm = (isWt: boolean) => {
  if (isWt) {
    if (wtInputValue.value) {
      wttyjTags.value.push(wtInputValue.value)
    }
    wtInputVisible.value = false
    wtInputValue.value = ''
  } else {
    if (hdInputValue.value) {
      hdtyjTags.value.push(hdInputValue.value)
    }
    hdInputVisible.value = false
    hdInputValue.value = ''
  }
}

// 加入收藏
const addSc = id => {
  addScApi(id).then(res => {
    ElMessage({
      type: 'success',
      message: '收藏成功',
    })

    getDataList()
  })
}

// 批量下线
const removeBatch = () => {
  let ids = []
  var selectRows = multipleTableRef.value.getSelectionRows()
  selectRows.forEach(element => {
    // 判断每个记录是否为已上线且没有下线的
    if (element.sfshenx == 1) {
      ids.push(element.id)
    }
  })
  if (ids.length == 0) {
    ElMessage({
      type: 'warning',
      message: '没有已上线的知识',
    })
  } else {
    xiaxiang(ids)
  }
}

// 下线知识
const xiaxiang = ids => {
  // 确认是否下线
  ElMessageBox.confirm(`确认是否下线?`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteZsApi(ids)
        .then(res => {
          ElMessage({
            type: 'success',
            message: '下线成功',
          })

          // 刷新树
          getDataList()
        })
        .catch(e => {
          ElMessage({
            type: 'error',
            message: '下线失败！！！！',
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消下线！！！！',
      })
    })
}

// 单个下线
const remove = id => {
  // 获取被选择的行的id
  let ids = []
  ids.push(id)

  xiaxiang(ids)
}

// 分类的值
const zslxIds = ref([])

// 分类属性映射
const props = {
  value: 'id',
  label: 'flmc',
  children: 'children',
}
const options = ref([])
const ruleFormRef = ref<FormInstance>()

// 表单校验
const rules = reactive<FormRules>({
  zsbt: [{ required: true, message: '知识标题不能为空', trigger: 'blur' }],
  zslxIds: [{ required: true, message: '知识分类不能为空', trigger: 'blur' }],
  wtnr: [{ required: true, message: '问题内容不能为空', trigger: 'blur' }],
  hdnr: [{ required: true, message: '回答内容不能为空', trigger: 'blur' }],
})
const onSubmit = () => {
  console.log('submit!')
}

// 移除附件时
// const handleRemove = (uploadFile, uploadFiles) => {
//   form.value.fj = null
// }

// 清空表单
const clearForm = () => {
  ; (form.value.id = null),
    (form.value.zsflmc = ''),
    (form.value.zsbt = ''),
    (form.value.zslxIds = []),
    (form.value.wtnr = ''),
    (form.value.wttyj = ''),
    (form.value.hdnr = ''),
    (form.value.hdtyj = ''),
    (form.value.fj = ''),
    (wttyjTags.value = []),
    (hdtyjTags.value = []),
    fileList.value = [],
    fileSuffix.value = ""
}

// 点击修改
const edit = async id => {
  // 清空表单
  clearForm()
  // 获取所有分类
  const res = await getTreeApi()
  options.value = res.data
  // 根据id获取数据
  getZsByIdApi(id).then(res => {
    form.value = res.data
    form.value.id = id
    // 问题同义句
    if (res.data.wttyj != null || res.data.wttyj != '') {

      var temp = res.data.wttyj.split('|')
      if (temp != null && temp.length > 0 && temp[0] != '') {
        wttyjTags.value = temp
      } else {
        wttyjTags.value = []
      }

    }
    // 回答同义句
    if (res.data.hdtyj != null || res.data.hdtyj != '') {

      var temp = res.data.hdtyj.split('|')
      if (temp != null && temp.length > 0 && temp[0] != '') {
        hdtyjTags.value = temp
      } else {
        hdtyjTags.value = []
      }
    }

    // 清空fileList数组  
    fileList.value = [];
    if (res.data.fj != null && res.data.fj != "") {
      // 设置文件RUL
      fileList.value.push({ name: "附件", url: res.data.fj })
      // 设置文件类型
      fileSuffix.value = (res.data.fj == null || res.data.fj == "") ? "" : res.data.fj.split('.').pop()
    }

    dialogType.value = '修改'
    dialogFormVisible.value = true
  })
}

// 修改或添加
const saveOrUpdate = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      dialogFormVisible.value = false

      if (form.value.id == null) {
        console.log('这个添加操作' + JSON.stringify(form))
        console.log('++++++++' + form.value.zsbt)
        addZsApi({
          zsbt: form.value.zsbt,
          zslxIds: form.value.zslxIds,
          wtnr: form.value.wtnr,
          wttyj: wttyjTags.value.join('|'),
          hdnr: form.value.hdnr,
          hdtyj: hdtyjTags.value.join('|'),
          fj: fileList.value.length == 0 ? null : fileList.value[0].url, // 只能上传一个附件
        }).then(res => {
          // 关闭对话框
          dialogFormVisible.value = false
          // 提示成功
          ElMessage({
            type: 'success',
            message: '添加成功！！！！',
          })

          // 刷新列表
          getDataList()

          dialogType.value = ''
        })
      } else {
        console.log('这是修改操作：' + JSON.stringify(form))
        updateZsApi({
          id: form.value.id,
          zsbt: form.value.zsbt,
          zslxIds: form.value.zslxIds,
          wtnr: form.value.wtnr,
          wttyj: wttyjTags.value.join('|'),
          hdnr: form.value.hdnr,
          hdtyj: hdtyjTags.value.join('|'),
          fj: fileList.value.length == 0 ? null : fileList.value[0].url, // 只能上传一个附件
        }).then(res => {
          // 关闭对话框
          dialogFormVisible.value = false
          // 提示成功
          ElMessage({
            type: 'success',
            message: '修改成功！！！！',
          })

          // 刷新列表
          getDataList()

          dialogType.value = ''
        })
      }
    } else {
      return false
    }
  })
}
// 点击添加
const add = async () => {
  // 清空表单
  clearForm()

  // 获取所有分类
  const res = await getTreeApi()
  options.value = res.data

  dialogFormVisible.value = true
  dialogType.value = '添加'
}

// 修改每页数
const sizeChangeHandle = val => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}
// 修改当前页
const currentChangeHandle = val => {
  pageIndex.value = val
  getDataList()
}

const resetData = () => {
  ; (queryData.keyWord = ''), (queryData.status = null), (queryData.zsfl = undefined)
  getDataList()
}

// 获取表格数据
const getDataList = () => {
  getListApi({
    page: pageIndex.value,
    limit: pageSize.value,
    keyWord: queryData.keyWord,
    zsflId: queryData.zsfl,
    status: queryData.status,
  }).then(res => {
    tableData.value = res.data.list
    total.value = res.data.totalCount
    loading.value = false
  })
}

getDataList()
</script>